<template>
  <div class="login-container">
    <el-form ref="loginForm" :model="loginForm"
             :rules="loginRules"
             class="login-form"
             auto-complete="on"
             label-position="left">

      <div class="title-container">

        <h3 class="title"> <img class="jicon" src="@/assets/favicon.png" alt="1">百胜测试中心</h3>
      </div>

      <el-form-item prop="username">
        <span class="svg-container">
          <svg-icon icon-class="user" />
        </span>
        <el-input
          ref="username"
          v-model="loginForm.username"
          placeholder="用户名"
          name="username"
          type="text"
          tabindex="1"
          auto-complete="on"
        />
      </el-form-item>

      <el-form-item prop="password">
        <span class="svg-container">
          <svg-icon icon-class="password" />
        </span>
        <!--show-password 看密码-->
        <el-input
          :key="passwordType"
          ref="password"
          v-model="loginForm.password"
          :type="passwordType"
          placeholder="密码"
          name="password"
          tabindex="2"
          auto-complete="on"
          @keyup.enter.native="handleLogin"
        />
        <span class="show-pwd" @click="showPwd">
          <!--显示眼睛的开关-->
          <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
        </span>
      </el-form-item>


      <el-button :loading="loading"
                 type="primary"
                 style="width:100%;margin-bottom:30px;"
                 @click.native.prevent="handleLogin">登录</el-button>

    </el-form>
  </div>
</template>

<script>
import Cookies from 'js-cookie'
import domain from '../../../domain.js'
const base = domain.target
import qs from 'qs'
// import Axios from 'axios'
import CryptoJS from 'crypto-js'
export default {
  name: 'Login',
  data() {
    return {
      loginForm: {
        //默认表单填好的值
        username: '',
        password: '',
        grant_type: 'password',
        client_id: 'client',
        client_secret: 123456
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur',message:"请输入用户名"}],
        password: [{ required: true, trigger: 'blur',message:"请输入密码"}],
        // authCode: [{ required: true, validator: checkCode, trigger: 'blur' }]
      },
      //是否显示加载状态
      loading: false,
      passwordType: 'password',
      //用于记录去过的路由
      routeQuery: {},
      verifyCode: null //验证码
    }
  },
  mounted() {

  },
  watch: {
    $route: {
      handler: function(route) {
        //如果两个值都有则返回后面的
        this.routeQuery = route.query
      },
      //当route变化时立即执行handler函数
      immediate: true
    }
  },
  methods: {
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        //记得聚焦
        this.$refs.password.focus()
      })
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        console.log(this.loginForm)
        if (valid) {
          this.loading = true
          // this.$store.dispatch('user/login', this.loginForm).then(() => {
          //   // 这个方法用于跟踪：我是从哪里跳到/login页面的，登录后我就返回哪里
          //   this.$router.push({ path: this.routeQuery || '/' })
          //   this.loading = false
          // }).catch(() => {
          //   this.loading = false
          // })
          sessionStorage.removeItem('curPath')
          sessionStorage.removeItem('taskResourceID')
          sessionStorage.removeItem('curSystem')
          const params = {
            grant_type: this.loginForm.grant_type,
            username: this.loginForm.username,
            password: this.encryp(this.loginForm.password),
            client_id: this.loginForm.client_id,
            client_secret: this.loginForm.client_secret
          }
          // alert(params.password)
          let userInfo = {
            "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJob3N0VGVhbSI6IiIsInNpZHMiOiIxMDAyLDEwMDMsMTAwNCwxMDA1LDEwMDYsMTAwNywxMDA4LDEwMDksMTAxMCwxMDExLDEwMTIsMTAxMywxMDE0LDEwMTUsMTAxNiwxMDE3LDEwMTgsMTAxOSwxMDIwLDEwMjEsMTAyMiwxMDIzLDEwMjQsMTAyNSwxMDI2LDEwMjcsMTAyOCwxMDI5LDEwMzAsMTAzMSwxMDMyLDEwMzMsMTAzNCwxMDM1LDEwMzYsMTAzNywxMDM4LDEwMzksMTA0MCwxMDQxLDEwNDIsMTA0MywxMDQ0LDEwNDUsMTA0NiwxMDQ3LDEwNDgsMTA0OSwxMDUwLDEwNTIsMTA1MywxMDU0LDEwNTUsMTA1NiwxMDU3LDEwNTgsMTA1OSwxMDYwLDEwNjEsMTA2MiwxMDYzLDEwNjQsMTA2NSwxMDY2LDEwNjcsMTA2OCwxMDY5LDEwNzAsMTA3MSwxMDczLDEwNzQsMTA3NSwxMDc2LDEwNzcsMTA3OCwxMDc5LDEwODAsMTA4MSwxMDgyLDEwODMsMTA4NCwxMDg1LDEwODYsMTA4NywxMDg4LDEwODksMTA5MCwxMDkxLDEwOTIsMTA5MywxMDk0LDEwOTUsMTA5NiwxMDk3LDEwOTgsMTA5OSwxMTAwLDExMDEsMTEwMiwxMTAzLDExMDQsMTEwNSwxMTA2LDExMDciLCJzdWIiOiJKRVRBVVRIIiwicm9sZUlkcyI6Iuezu-e7n-euoeeQhuWRmCIsImhvc3RUcmliZSI6IiIsInJlYWx1c2VybmFtZSI6IueuoeeQhuWRmCIsImRldmVsb3BtZW50Q2VudGVyIjoiIiwiaWF0IjoxNjg5MDY2NzMxLCJ1c2VybmFtZSI6InRlc3QwMSIsInN0YXR1cyI6IjEifQ.4cmAx4SfQ0XQARzwM9TMgmQv-q9EbAI4sihAt3ffzZQ",
            "token_type": "bearer",
            "expires_in": 21599,
            "scope": "webclients",
            "hostTeam": null,
            "hostTribe": null,
            "realusername": "管理员",
            "userResourceID": 15070171671118848,
            "developmentCenter": null,
            "userType": "local",
            "username": "test01",
            "status": "1"
          }
          Cookies.set('token', userInfo.access_token)
          localStorage.setItem('token', userInfo.access_token)
          Cookies.set('userName', userInfo.username)
          Cookies.set('userRId', userInfo.userResourceID)
          Cookies.set('userpwd', 123456)
          Cookies.set('userType', userInfo.userType)
          Cookies.set('realusername', userInfo.realusername)
          Cookies.set('realusername', userInfo.realusername)
          sessionStorage.setItem('userName', userInfo.username)
          // this.getBuildMainMenu() // 注释
          this.loading = false

        } else {
          // this.verifyCode.refresh() // 刷新码
          return false
        }
      })
    },
    // 获取配置的权限系统
    acquireSystemList(){
      new Promise((resolve => {
        this.$post(`${base}/basic/dataPrivilege/userSystemPrivileges`,{}).then((res) => {
          console.log("res",res)
          resolve(res.data.obj)
        })
      })).then((data)=>{
        console.log("配置的sys",data)
        // 没有配置权限
        if (data.length ==0){
          console.log("请求全部系统")
          this.$message.error("暂无系统权限，请联系管理配置")         // this.queryAllSystem()
          this.getBuildMainMenu()
        }else{
          console.log("配置的权限",data)
          let defaultsys = data.filter((item,index)=>{
            return item.defaultOption ==1
          })
          if (defaultsys.length>0){
            // 将这个系统id抽出来 存到vuex 和localstorage中
            this.$store.commit("systemPermission/setActiveSystem",defaultsys[0].id)
            localStorage.setItem("activeSystem",defaultsys[0].id)
            // 将这个系统抽出来 存到vuex 和localstorage中
            this.$store.commit("systemPermission/setChosenSystemList",defaultsys)
            localStorage.setItem("chosenSystemList",JSON.stringify( defaultsys))
          }else{
            // 没设置默认系统
            this.$store.commit("systemPermission/setActiveSystem","")
            localStorage.setItem("activeSystem","") //

            this.$store.commit("systemPermission/setChosenSystemList",data)
            localStorage.setItem("chosenSystemList",JSON.stringify( data)) // 所有系统扔进去
          }

          localStorage.setItem("systemList",JSON.stringify(data))
          this.$store.commit("systemPermission/setSystemList",data)
          localStorage.setItem("allSystemList",JSON.stringify([]))
          this.$store.commit("systemPermission/setAllSystemList",[])
          this.getBuildMainMenu()
        }
      })
    },
    encryp(val = '') {
      const key = CryptoJS.enc.Utf8.parse('mYIasdnZbdWx6vJ4');
      const srcs = CryptoJS.enc.Utf8.parse(val);
      const encrypted = CryptoJS.AES.encrypt(srcs, key, {mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7});
      return encrypted.toString();
    },
    async getBuildMainMenu() {
      // const res = await getBuildMainMenu(qs.stringify({menuTo:4}))
      // `${base}/basic/buildMainMenu`

      this.$post(`${base}/basic/buildMainMenu`, qs.stringify({menuTo:1}),{},3).then((res)=>{
        if (res.data.code == 20000) {
          const menuData = res.data.obj
          console.log("menuData",menuData)
          // 登录默认测管菜单
          sessionStorage.setItem('menuItems', JSON.stringify(menuData))
          sessionStorage.setItem('menuItems', JSON.stringify(menuData))
          sessionStorage.setItem('tmMenuItems', JSON.stringify(menuData))
          sessionStorage.setItem('curSystem', 1)
          Cookies.set('menuItems', JSON.stringify(menuData))
          localStorage.setItem('menuItems', JSON.stringify(menuData))
          // this.$store.dispatch('settings/changeCurSystem', 1)
          let arr = []
          // const topMenuData = []
          const topMenuData = [
            {
              "id": null,
              "createTime": null,
              "editTime": null,
              "createUser": null,
              "editUser": null,
              "resourceID": "16321298682430464",
              "name": "workbenchWait",
              "text": "我的工作台",
              "type": null,
              "ip": null,
              "port": null,
              "fullPath": null,
              "menuFrom": 1,
              "menuTo": 1,
              "code": "11669084853821",
              "children": [],
              "alien": false,
              "loadContent": false
            },
            {
              "id": null,
              "createTime": null,
              "editTime": null,
              "createUser": null,
              "editUser": null,
              "resourceID": "16321299442385920",
              "name": "leaderShipView",
              "text": "领导视图",
              "type": null,
              "ip": null,
              "port": null,
              "fullPath": null,
              "menuFrom": 1,
              "menuTo": 1,
              "code": "11669084865417",
              "children": [],
              "alien": false,
              "loadContent": false
            }
          ]

          menuData.map(item => {
            arr = arr.concat(item.children)
          })
          console.log("arr",arr)

          sessionStorage.setItem('topMenu', JSON.stringify(topMenuData))
          localStorage.setItem('topMenu', JSON.stringify(topMenuData))
          if (res.data.obj.length == 0) {
            this.message = '当前用户没有菜单权限，请联系项目经理'
            Cookies.remove('user')
            Cookies.remove('token')
            Cookies.remove('refresh_token')
            Cookies.remove('realusername')
          }
          this.$nextTick(() => {
            if (Cookies.set('userName') == 'Admin' || topMenuData.length == 0) {
              // const data = res.data.obj[0].children
              // const path = '/' + data[0].name
              // this.$router.push({path: path})
            } else {

              // let path = this.$route.query.routeQuery ? this.$route.query.routeQuery:topMenuData[0].name
              // this.$router.push({path,query:{...this.$route.query}})
            }
            console.log("this.routeQuery",this.routeQuery)
            if (this.routeQuery.redirect){
              console.log("登录跳转加参")
              this.$router.push({path:this.routeQuery.redirect,query:this.routeQuery})
            }else{
              this.$router.push({path:"/workbenchWait"})
            }
          })
        }
      })
    },
  }
}
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg:#283443;
$light_gray:#fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui CssPartial */
.login-container {
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }
}
</style>

<style lang="scss" scoped>
$bg:#2d3a4b;
$dark_gray:#889aa4;
$light_gray:#eee;

.login-container {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;

  .login-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    padding: 160px 35px 0;
    margin: 0 auto;
    overflow: hidden;
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;
    vertical-align: bottom;
    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
}
  .yzmBtn{
    width: 105px;
    height: 40px;
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }

  .jicon{
    width: 2rem;
    height: 2rem;
    vertical-align: bottom;
  }
</style>
